<?php
// +----------------------------------------------------------------------
// | LaySNS
// +----------------------------------------------------------------------
// | QQ交流群: 227552979
// +----------------------------------------------------------------------
// | 开源协议  https://mit-license.org
// +----------------------------------------------------------------------
// | github开源项目：https://gitee.com/yunyang0726/LaySNS
// +----------------------------------------------------------------------
namespace app\index\controller;
use app\common\controller\HomeBase;
use app\common\model\Article;
use app\common\model\ArticleCategory;
use app\common\model\Collect;
use app\common\model\SeoLog;
use app\common\service\UploadService;
use QL\Ext\DImage;
use think\facade\Cache;
use think\facade\Db;


class Job extends HomeBase
{
    protected $params;
    public function initialize()
    {

        parent::initialize();
        $params=$this->params;
        if (!isset($params['key'])||!$params['key']) {
            return fail('没有填写JobKey');
        }
        $otaConfig = sysconfig('key');
        if ($otaConfig['job_key'] != $params['key']) {
            return fail('JobKey不正确');
        }
    }
    //定时清理缓存
    public function clearCache()
    {
        Cache::clear();
        authCheck();
        $this->success('清理缓存成功');
    }
    //定时清理每月浏览量 每月1日0点执行
    public function clearMonthView()
    {
        (new Article())->where('id','>',0)
            ->save(['month_view'=>0]);
    }

    //定时清理每周浏览量 每周0点执行
    public function clearWeekView()
    {
        (new Article())->where('id','>',0)
            ->save(['week_view'=>0]);
    }
    //定时清理每周浏览量 每天0点执行
    public function clearDayView()
    {
        (new Article())->where('id','>',0)
            ->save(['day_view'=>0]);
        if(date('w')==1){
            (new Article())->where('id','>',0)
                ->save(['week_view'=>0]);
        }
        if(date('d')==1){
            (new Article())->where('id','>',0)
                ->save(['month_view'=>0]);
        }
    }
    //检测文章广告到期隐藏
    public function hideExpiredAdArticle()
    {
        $res=(new Article())
            ->where('is_ad',1)
            ->where('finish_time','<',time())
            ->save(['status'=>0]);
        if($res){
            return success('成功更新');
        }
    }

    //定时发布
    public function scheduledRelease()
    {
        $updatedAt=time();
        $prefix=env('database.PREFIX');
        $list=Db::query("select a.id from ".$prefix."article a inner join ".$prefix."article_attribute b  on a.id=b.article_id where a.status=0 and check_status =-1 and publish_time< ".$updatedAt." and publish_time>update_time;");
        $count=count($list);
        if($count) {
            $ids = array_column($list, 'id');
            $setField['status'] = 1;
            $setField['update_time'] = $updatedAt;
            (new Article())->whereIn('id', $ids)->save($setField);
            if (Cache::has('newArticle')) {
                Cache::delete('newArticle');
            }
        }
        return success('定时发布'.$count.'条');
    }

    //定时采集 采集官方的
    public function collect()
    {
        $data=$this->params;
        $page=isset($data['page'])?$data['page']:1;
        $where=[
            'site_name'=>$data['site_name'],
            'page'=>$page,
        ];
        $k = 0;
        for ($i=0;$i<=$page;$i++) {
            $result = getJsonData('Collect', 'list', $where, 60);
            if (is_array($result) && $result['code'] == 1) {
                $result['code'] = 0;
                $list = $result['data'];
                foreach ($list as $v) {
                    $res = (new Collect())->download($v['uniquekey'], 'article');
                    if ($res !== false && $res == 0) {
                        $k++;
                    }
                }
            } else {
                return fail('获取列表失败');
            }
        }
        return success('采集到新的数据' . $k . '条');
    }



    //百度收录推送
    public function sendToBaidu()
    {
        return SeoLog::pushToBaidu('today');
    }

    //发布文章的API
    public function publish(){

        //必传参数
        $only = ['title', 'category_id', 'cover_img', 'content', 'attach', 'reward_account', 'reward_name'];
        $rule = [
            'title|标题' => 'require',
            'category_id|分类' => 'require|number',
            'content|内容' => 'require'
        ];
        $data = validate_ext($only, $rule);

        if (isset($data['code']) && $data['code'] === 0) {
            return json($data);
        }

        $title = remove_xss($data['title']);

        $data['seo_title'] = $title;


        $content = htmlspecialchars_decode(html_entity_decode($data['content']));

        if(sysconfig('article.downpic')){
            $content=(new DImage())->run([
                'content' => $content,
                'www_root' => $_SERVER['DOCUMENT_ROOT'],
                'image_path' => '/uploads/' . date('Y') . '/' . date('md'),
            ]);
        }

        $data['content'] = $content;
        $cdk = Article::getCDK($content,$title);

        $data['category_id'] = remove_xss($data['category_id']);
        if (isset($data['attachlink'])) {
            $data['attachlink']['user_id'] = $userId;
        }
        $data['keywords'] = $cdk['K'];
        if (isset($data['reward_account'])) {
            //要奖励
            $data['reward_status'] = 0;
        }
        $base64 = $data['cover_img'];
        if ($base64) {
            $resl = UploadService::upBase64($base64);
            if ($resl['code'] == 1) {
                $data['cover_img'] = $resl['data']['url'];
            }
        } else {
            $data['cover_img'] = $cdk['C'];
        }
        if(!empty($data['attach'])){
            $attach=json_decode($data['attach'],true);
            $arr=[];
            foreach ($attach as $v){
                if($v){
                    $arr[]=[
                        'url'=>$v
                    ];
                }
            }
            if(!empty($arr)) {
                $data['attachlink']['urls'] = $arr;
            }
        }
        try {
            (new Article())->createNew($data);
            session('tg_suijima', null);
            $ret = [
                'code' => 1,
                'msg' => "投稿成功",
                'data' => ['exempt_num' => 0, 'reload' => 2]
            ];
        } catch (\Exception $e) {
            $ret = [
                'code' => 0,
                'msg' => $e->getMessage(),
                'data' => []
            ];
        }
        return json($ret);


    }


    public function createSitemap() {
        Article::createSitemap();
        echo '网站地图更新成功！可以到网站根目录下的<a target="_blank" href="'.domain_url('/sitemap.xml').'">sitemap.xml</a>查看！';
    }
}
